package num233;

import javax.swing.plaf.metal.MetalLookAndFeel;

/**
 * 233. 数字 1 的个数
 * 题目：https://leetcode-cn.com/problems/number-of-digit-one/
 * 三叶姐题解: https://leetcode-cn.com/problems/number-of-digit-one/solution/gong-shui-san-xie-jiang-shu-wei-dp-wen-t-c9oi/
 * 三叶姐
 */
public class Solution {
    public int countDigitOne(int n) {
        String s = String.valueOf(n);
        int m = s.length();
        if (m == 1) return n > 0 ? 1 : 0;
        int[] ps = new int[m], ss = new int[m];
        ss[0] = Integer.parseInt(s.substring(1));
        for (int i = 1; i < m - 1; i++) {
            ps[i] = Integer.parseInt(s.substring(0, i));
            ss[i] = Integer.parseInt(s.substring(i + 1));
        }
        ps[m - 1] = Integer.parseInt(s.substring(0, m - 1));

        int ans = 0;
        for (int i = 0; i < m; i++) {
            int x = s.charAt(i) - '0', len = m - i - 1;
            int prefix = ps[i], suffix = ss[i];
            int tot = 0;

            tot += prefix * Math.pow(10, len);
            if (x == 0) {

            } else if (x == 1) {
                tot += suffix + 1;
            } else {
                tot += Math.pow(10, len);
            }
            ans += tot;
        }
        return ans;
    }

    public static void main(String[] args) {
        System.out.println(new Solution().countDigitOne(200));
    }
}

